package lucid.hrms.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

public class CommonHelper {

	private static final Logger logger = Logger.getLogger(CommonHelper.class);

	Set<Object> set = new HashSet<Object>();
	List<Object> list = new ArrayList<Object>();
	Map<Object, Object> map = new HashMap<Object, Object>();

	public static <T> String toString(Class<T> clazz, T t) {
		StringBuilder builder = new StringBuilder();
		builder.append(clazz.getSimpleName() + "[");
		Method[] methods = clazz.getMethods();
		for (int index = 0; index < methods.length; index++) {
			Method method = methods[index];
			if (isGetter(method)) {
				try {
					if (index > 0) {
						builder.append(", ");
					}
					builder.append(getNameWithFirstCharacterIsLowerCased(method.getName()));
					builder.append("=");
					builder.append(method.invoke(t));
				} catch (IllegalArgumentException e) {
					logger.error(e);
				} catch (IllegalAccessException e) {
					logger.error(e);
				} catch (InvocationTargetException e) {
					logger.error(e);
				}
			}
		}
		builder.append("]");

		return builder.toString();
	}

	public static boolean isGetter(Method method) {
		if (!(method.getName().startsWith("get") || (method.getName().startsWith("is") && method.getReturnType().equals(boolean.class)))) {
			return false;
		}
		if (method.getParameterTypes().length != 0) {
			return false;
		}
		if (void.class.equals(method.getReturnType())) {
			return false;
		}
		return true;
	}

	public static boolean isSetter(Method method) {
		if (!method.getName().startsWith("set")) {
			return false;
		}
		if (method.getParameterTypes().length != 1) {
			return false;
		}
		return true;
	}

	public static String getNameWithFirstCharacterIsLowerCased(String name) {
		int nameIndex = 3; // "get"
		if (name.startsWith("is")) {
			nameIndex = 2;
		}
		if (name.length() > nameIndex) {
			return name.substring(nameIndex, nameIndex + 1).toLowerCase().concat(name.substring(nameIndex + 1, name.length()));

		} else {
			return "";
		}
	}
}
